package com.jiukuaidao.library.net;

import android.text.TextUtils;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Author : H_Joker
 * Date : 2016/5/12
 * Description :
 */
public class RetroCallBackImpl<T> implements retrofit2.Callback<RootResult<T>> {

    private MyRetroCallBack<T> mCallBack;

    public void setCallBack(MyRetroCallBack callBack) {
        mCallBack = callBack;
    }

    @Override
    public void onResponse(Call<RootResult<T>> call, Response<RootResult<T>> response) {
        if (mCallBack != null) {
            RootResult<T> bean = response.body();
            if (HttpURLConnection.HTTP_OK == response.code()) {
                if (bean.code == 1) {
                    mCallBack.onSuccess(bean.result, String.valueOf(bean.code), bean.msg);
                } else {
                    mCallBack.onFail(bean.result, String.valueOf(bean.code), bean.msg);
                }
            } else {
                if (bean != null) {// 凡是非200，response.body()就为null，所以这里没什么卵用
                    mCallBack.onError(null, response.code(), TextUtils.isEmpty(bean.msg) ? "网络异常，刷新试试~" : bean.msg);
                } else {
                    mCallBack.onError(null, response.code(), "网络异常，刷新试试~");
                }
            }
        }
    }

    @Override
    public void onFailure(Call<RootResult<T>> call, Throwable t) {
        if (mCallBack != null) {
            mCallBack.onError(t, -1, "网络异常，刷新试试~");
        }
    }
}
